<template>
  <div 
    class="text-renderer" 
    :style="textStyle"
    v-html="displayText"
  ></div>
</template>

<script>
export default {
  name: 'TextRenderer',
  props: {
    component: {
      type: Object,
      required: true
    },
    config: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'design'
    },
    testData: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    textStyle() {
      const { content = {} } = this.component
      return {
        fontSize: `${content.fontSize || 14}px`,
        fontWeight: content.fontWeight || 'normal',
        textAlign: content.align || 'left',
        color: content.color || '#000000',
        lineHeight: '1.5',
        whiteSpace: 'pre-wrap',
        wordBreak: 'break-word'
      }
    },
    
    displayText() {
      const { content = {} } = this.component
      let text = content.text || ''
      
      // 在预览和生成模式下，替换参数变量
      if (this.mode !== 'design') {
        text = this.replaceParamVariables(text)
      }
      
      return text
    }
  },
  methods: {
    replaceParamVariables(text) {
      // 替换 {{paramCode}} 格式的变量
      return text.replace(/\{\{([^}]+)\}\}/g, (match, paramCode) => {
        const value = this.getParamValue(paramCode.trim())
        return value !== null ? value : match
      })
    },
    
    getParamValue(paramCode) {
      // 从测试数据中获取参数值
      if (this.testData && this.testData[paramCode] !== undefined) {
        return this.testData[paramCode]
      }
      
      // 从参数配置中获取默认值或显示名称
      const paramConfig = this.findParamConfig(paramCode)
      if (paramConfig) {
        return paramConfig.paramName || paramCode
      }
      
      return null
    },
    
    findParamConfig(paramCode) {
      const { paramGroups = [] } = this.config
      const allParams = this.getAllParamItems(paramGroups)
      return allParams.find(param => param.paramCode === paramCode)
    },
    
    getAllParamItems(groups) {
      const params = []
      
      function extractParams(groupList) {
        groupList.forEach(group => {
          if (group.paramItems) {
            params.push(...group.paramItems)
          }
          if (group.childGroups) {
            extractParams(group.childGroups)
          }
        })
      }
      
      extractParams(groups)
      return params
    }
  }
}
</script>

<style scoped>
.text-renderer {
  width: 100%;
  height: 100%;
  padding: 4px;
  box-sizing: border-box;
}
</style>